import * as React from 'react'
import { Footer } from './Footer'
import { AddTodo } from '../containers/AddTodo';
import { VisibilityFilters, addTodo, completeTodo, setVisibilityFilter } from '../action';
import { connect } from 'react-redux';
import { TodoList } from './TodoList';

class App extends React.Component<{ dispatch, visibleTodos, visibilityFilter }, null>{

    render()
    {
        // Injected by connect() call:
        const { dispatch, visibleTodos, visibilityFilter } = this.props
        return <div>
            <AddTodo
                onAddClick={text => dispatch(addTodo(text))}
            />
            <TodoList
                todos={visibleTodos}
                onTodoClick={index =>
                    dispatch(completeTodo(index))
                } />
            <Footer
                filter={visibilityFilter}
                onFilterChange={nextFilter =>
                    dispatch(setVisibilityFilter(nextFilter))
                } />
        </div>
    }
}

function selectTodos(todos, filter)
{
    switch (filter) {
        case VisibilityFilters.SHOW_ALL:
            return todos
        case VisibilityFilters.SHOW_COMPLETED:
            return todos.filter(todo => todo.completed)
        case VisibilityFilters.SHOW_ACTIVE:
            return todos.filter(todo => !todo.completed)
    }
}

// Which props do we want to inject, given the global state?
// Note: use https://github.com/faassen/reselect for better performance.
function select(state)
{
    return {
        visibleTodos: selectTodos(state.todos, state.visibilityFilter),
        visibilityFilter: state.visibilityFilter
    }
}

// 包装 component ，注入 dispatch 和 state 到其默认的 connect(select)(App) 中；
export var AppContainers = connect(select)(App)